//
//  Restaurant.m
//  Reservation
//
//  Created by Wai Man Chan on 2014/2/21.
//  Copyright (c) 2014年 CHAN, Wai Man. All rights reserved.
//

#import "Restaurant.h"

@interface Restaurant () {
    NSDictionary *dictionary;
    UIImage *logo;
    NSArray *photoList;
    CLPlacemark *placemark;
}
@end

@implementation Restaurant
@synthesize durationPerMeal, sid;
- (id)initWithID:(long long)restaurantID {
    self = [super init];
    NSString *InfoAddress = [NSString stringWithFormat:@"http://happywaiman.dlinkddns.com/Reserve/Company/Info.php?id=%lld", restaurantID];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:InfoAddress]];
    dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    durationPerMeal = ((NSNumber *)(dictionary[@"Meal Duration"])).doubleValue;
    sid = restaurantID;
    return self;
}
//Info Retrieve
- (NSString *)name { return dictionary[@"CompanyName"]; }
- (NSString *)phoneNumber { return dictionary[@"phoneNumber"]; }
- (NSString *)address { return dictionary[@"StoreAddr"]; }
- (UIImage *)restaurantLogo {
    if (logo) return logo;
    NSURL *url = [NSURL URLWithString:dictionary[@"LogoAddress"]];
    logo = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    if (!logo) logo = [UIImage imageNamed:@"Chinese".lowercaseString];
    return logo;
}
- (NSArray *)listOfPicture {
    NSURL *url = [NSURL URLWithString:dictionary[@"ListofPicture"]];
    if (photoList == NULL) {
        NSData *data = [NSData dataWithContentsOfURL:url];
        if (data) photoList = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
    }
    return photoList;
}

- (BOOL)currentlyAvailable:(unsigned short)numberOfSeats {
#define currentAvailableWebsitePattern @"http://happywaiman.dlinkddns.com/Reserve/Company/table.php?rid=%lld&seat=%d"
    NSString *str = [NSString stringWithFormat:currentAvailableWebsitePattern, self.sid, numberOfSeats];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
    if (data.length) return atoi(data.bytes);
    return false;
}

+ (NSDateFormatter *)dateFormatter {
    static NSDateFormatter *formatter = NULL;
    if (formatter == NULL) {
        formatter = [NSDateFormatter new];
        [formatter setDateFormat:@"HH:mm:ss"];
    }
    return formatter;
}
- (NSDate *)openHour {
    return [[Restaurant dateFormatter] dateFromString:dictionary[@"OpenHour"]];
}
- (NSDate *)closeHour {
    return [[Restaurant dateFormatter] dateFromString:dictionary[@"CloseHour"]];
}

- (CLPlacemark *)placemark {
    if (placemark == NULL) {
        CLGeocoder *gecoder = [[CLGeocoder alloc] init];
        [gecoder geocodeAddressString:self.address completionHandler:^(NSArray *placemarks, NSError *error) {
            if (placemarks.count) {
                placemark = placemarks[0];
            }
        }];
    }
    return placemark;
}

@end
